// pages/relation/edit_relation_page.js
import {FamilyTreeDrawer} from '../../utils/drawer/family_tree_drawer'
const app = getApp()

//操作类型枚举
var Operation= {
  EDIT_PERSON: 0,
  ADD_FATHER: 1, 
  ADD_MOTHER: 2,
  ADD_HUSBAND: 3,
  ADD_WIFE: 4,
  ADD_BROTHER: 5,
  ADD_CHILD: 6,
  DELETE_PERSON: 7
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    curr_person: 0,  //当前选中人
    curr_person_name: '',  //当前选中人的姓名
    family_data: null,  //当前所有人员数据，等同于接口select_family的返回数据
    self_level: 0, //自己在当前家族树中的是第几代，从1开始
    other_family_exist: false, //是否有其他家族存在

    Operation: Operation,
    curr_operations: [
      Operation.EDIT_PERSON,
      Operation.ADD_FATHER,
      Operation.ADD_MOTHER,
      Operation.ADD_HUSBAND,
      Operation.ADD_BROTHER,
      Operation.ADD_CHILD,
      Operation.DELETE_PERSON
    ],  //当前显示（允许）的操作，是包含枚举Operation的数组。初始的时候考虑最多的情况，用来确定topbar的高度。

    bar_height: null, // topbar的高度，单位像素
    placeholder: 
    `一. 请选中人员进行操作。
     二. 一个家族里夫妻双方只能有一方存在长辈或兄弟姊妹，以避免混乱。双方的可以存在不同的家族中。
     三. 从家族中移除人员，被移除人员移除后如果在其他家族中存在，保留人员及个人资料；移除后如果在其他家族中不存在，不保留人员，并且移除前需要先手动清空个人资料(个人记事和相片)才能移除。不能随意移除，移除权限控制：
     &nbsp;&nbsp;&nbsp;&nbsp;1. 夫妻双方存在长辈或兄弟姊妹的一方后移除。
     &nbsp;&nbsp;&nbsp;&nbsp;2. 一人如果既有长辈(或兄弟姊妹)又有后代不能直接移除。
     &nbsp;&nbsp;&nbsp;&nbsp;3. 长辈或兄弟姊妹如果自己不是添加者就不能移除。
     `,

     has_edit_person: false, //是否编辑过人员
     last_edit_family_data: null,  //最近一次编辑人员后的家族数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //查询有没有其他家族存在
    app.httpRequest('get_family_list', {}, res => {
      console.log('family list: ', res)
      for (let i = 0; i < res.length; i++) {
        if (res[i].family_id != app.globalData.select_family_id) {
          this.setData({
            other_family_exist: true
          })
          break
        } 
      }
    }, res => {
      console.log('get family list failed: ', res)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    this.tree_drawer = new FamilyTreeDrawer({
      can_select_person: true,   //是否可以选中人
      cancel_select_person: false,  //点击空白位置(人以外的位置)是否可取消选中人
      can_long_press_person: false  //是否支持长按人
    }) //家族树绘制器
    this.tree_drawer.RegisterSelectPersonCallback(this.onSelectPerson.bind(this))

    // 设置topbar的高度
    wx.createSelectorQuery()
      .select('.bar')
      .fields({
        node: true,
        size: true,
      })
      .exec(this.initBar.bind(this))

    // canvas2D
    wx.createSelectorQuery()
      .select('#canvas2D')
      .fields({
        node: true,
        size: true,
      })
      .exec(this.initCanvas.bind(this))
  },

  initBar(res) {
    const width = res[0].width
    const height = res[0].height
    const bar = res[0].node
    this.setData({
      bar_height: height + 10,  //这里加10个像素，不然按钮变更后画布有稍微的向上移动，暂时找不到原因。
      curr_operations: [],      //同时将按钮清空，初始的按钮状态仅用来测量topbar的高度
    })
  },

  initCanvas(res) {
    const width = res[0].width
    const height = res[0].height

    const canvas = res[0].node
    // 不支持2d
    if (!canvas) {
      console.log('not support canvas!')
      return
    }
    const ctx = canvas.getContext('2d')

    const dpr = 750 / wx.getSystemInfoSync().windowWidth  //听说getSystemInfoSync返回的pixelRatio有可能不准。
    canvas.width = width * dpr
    canvas.height = height * dpr
    ctx.scale(dpr, dpr)

    this.tree_drawer.SetContext(ctx, width, height) //传入画布及画布整个的大小

    //渲染循环
    const renderLoop = () => {
      this.tree_drawer.Render()
      canvas.requestAnimationFrame(renderLoop)
    }
    canvas.requestAnimationFrame(renderLoop)

    //加载家族数据
    this.tree_drawer.SwitchFamily(app.globalData.select_family_id)

  },

  //选中某个人的回调
  onSelectPerson(personId) {
    //console.log('select person:', personId)
    if (!this.data.family_data) {
      this.setData({
        family_data: this.tree_drawer.GetCurrWithLevelData()
      })
      //获取自己是第几代，用来判断权限
      for (let i = 0; i < this.data.family_data.length; i++) {
        let couple = this.data.family_data[i]
        if (app.globalData.curr_person == couple.wife || app.globalData.curr_person == couple.husband) {
          this.setData({
            self_level: couple.level
          })
          break
        }
      }
    }

    //获取选中人姓名
    let person_name = '';
    for (let i = 0; i < this.data.family_data.length; i++) {
      let couple = this.data.family_data[i]
      if (couple.wife && couple.wife == personId) {
        person_name = couple.wife_name
      }
      if (couple.husband && couple.husband == personId) {
        person_name = couple.husband_name
      }
    }

    this.setData({
      curr_person: personId,
      curr_person_name: person_name
    })
    this.judgePersonRight(personId)

  },

  //判断某人可以进行哪些操作
  judgePersonRight(personId) {
    if (0 == personId) {
      this.setData({
        curr_operations: []
      })
      return
    }

    let family_data = this.data.family_data
    //console.log('----family:', personId, this.data.family_data)
    if (!family_data || family_data.length == 0) {
      this.setData({
        curr_operations: []
      })
      return
    }

    //先建立缓存
    let id_cache = {}      //child couple id -> child couple
    let parent_cache = {}     //parent couple id -> child couple array
    let curr_couple = null    //personId所在的couple
    let is_wife = false       //当前人的性别
    let another_half = 0         //另一半的id
    for (let i = 0; i < family_data.length; i++) {
      let couple = family_data[i]
      if (couple.wife == personId || couple.husband == personId) {
        curr_couple = couple
        is_wife = (couple.wife == personId)
        another_half = is_wife ? couple.husband : couple.wife
      }
      id_cache[couple.child] = couple
      if (couple.parent != 0) {
        if (parent_cache[couple.parent]) {
          parent_cache[couple.parent].push(couple)
        } else {
          parent_cache[couple.parent] = [couple]
        }
      }
    }
    
    if (!curr_couple) {
      this.setData({
        curr_operations: []
      })
      return  
    }

    //分析权限
    let ops = []
    ops.push(Operation.EDIT_PERSON)
    {
      //丈夫和妻子
      if (is_wife) {
        if (another_half == 0) {
          ops.push(Operation.ADD_HUSBAND)
        } 
      } else {
        if (another_half == 0) {
          ops.push(Operation.ADD_WIFE)
        }
      }
    } 
    let has_own_parent = false  //是否存在自己的长辈或兄弟姊妹
    {
      //父亲和母亲、兄弟姊妹
      if (curr_couple.parent) {
        let is_own_parent = false  //是否是己方的长辈
        if (curr_couple.child_male) {
          if (is_wife) {
            //丈夫已经有长辈了，妻子不能有了
          } else {
            is_own_parent = true
          }
        } else {
          if (is_wife) {
            is_own_parent = true
          } else {
            //妻子已经有长辈了，丈夫不能有了
          }
        }

        if (is_own_parent) {
          has_own_parent = true
          if (curr_couple.parent in id_cache) {
            let parent_couple = id_cache[curr_couple.parent]
            if (parent_couple.husband == 0) {
              ops.push(Operation.ADD_FATHER)
            }
            if (parent_couple.wife == 0) {
              ops.push(Operation.ADD_MOTHER)
            }
            ops.push(Operation.ADD_BROTHER)
          }
        }

      } else {
        ops.push(Operation.ADD_FATHER);
        ops.push(Operation.ADD_MOTHER);
        ops.push(Operation.ADD_BROTHER)
      }
    }

    //子女
    ops.push(Operation.ADD_CHILD)
    //删除人员
    let cannot_remove = false
    if (has_own_parent) {
      if (another_half) {
        //夫妻双方存在长辈或兄弟姊妹的一方后删除
        cannot_remove = true
        console.log('r1')
      } else {
        if (curr_couple.child in parent_cache && parent_cache[curr_couple.child].length > 0) {
          //有子女
          //又有长辈又有子女不能直接删除
          cannot_remove = true
          console.log('r2')
        }
      }
    }
    if (this.data.self_level && this.data.self_level >= curr_couple.level) {
      //删除的是长辈或兄弟姊妹
      if (personId != app.globalData.curr_person) {
        if (is_wife) {
          if (curr_couple.wife_creator != app.globalData.curr_person) {
            cannot_remove = true
            console.log('r3')
          }
        } else {
          if (curr_couple.husband_creator != app.globalData.curr_person) {
            cannot_remove = true
            console.log('r4')
          }
        }
      }
    }

    if (!cannot_remove) {
      ops.push(Operation.DELETE_PERSON)
    }

    this.setData({
      curr_operations: ops
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  //刷新页面
  onClearCache() {
    if (this.tree_drawer) {
      this.tree_drawer.ClearTapCache()
    }
    this.setData({
      curr_operations: []
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.has_edit_person) {
      //有编辑过人员
      let pages = getCurrentPages()  //获取当前页面js里面的pages里的所有信息。
      let prevPage = pages[pages.length - 2]  //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。
      prevPage.refreshFamilyData(this.data.last_edit_family_data)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //画布回调函数
  onTouchStart(e) {
    if (e.touches && e.touches.length == 1){
      //单指点击
      console.log('+++++++++ single start', e)
      this.tree_drawer.OnDragStart(e)
      this.single_finger = true
      this.double_finger = false
    }
    else if (e.touches && e.touches.length == 2){
      console.log('+++++++++++++double start', e)
      this.tree_drawer.OnScaleStart(e)
      this.single_finger = false
      this.double_finger = true
    }
  },

  onTouchMove(e) {
    if (e.touches && e.touches.length == 1){
      //单指点击
      this.tree_drawer.OnDragging(e)
    }
    else if (e.touches && e.touches.length == 2){
      //双指
      this.tree_drawer.OnScaling(e)
    }
  },

  onTouchCancel(e) {
    if (this.single_finger) {
      this.tree_drawer.OnDragEnd(e)
    }
    if (this.double_finger) {
      this.tree_drawer.OnScaleEnd(e)
    }
  },

  onTouchEnd(e) {
    if (this.single_finger) {
      this.tree_drawer.OnDragEnd(e)
    }
    if (this.double_finger) {
      this.tree_drawer.OnScaleEnd(e)
    }
  },

  //添加父亲
  onAddFather() {
    if (0 == this.data.curr_person) {
      return
    }
    if (this.data.other_family_exist) {
      wx.showActionSheet({
        itemList: ['新增人员', '从其它家族中选择已有人员'],
        success: res => {
          console.log(res.tapIndex)
          if (res.tapIndex == 0) {
            //新增人员
            wx.navigateTo({
              url: '../relation/add_father?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name)
            })

          } else if (res.tapIndex == 1) {
            //从其它家族中选择已有人员
            app.navigateToOtherFamilyMember(1, (selectFamilyId, selectPersonId) => {
              console.log('select person:', selectPersonId)

              if (!this.data.family_data) {
                this.setData({
                  family_data: this.tree_drawer.GetCurrWithLevelData()
                })
              }
              let family_data = this.data.family_data
              for (let i = 0; i < family_data.length; i++) {
                if (family_data[i].husband != 0 && family_data[i].husband == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
                if (family_data[i].wife != 0 && family_data[i].wife == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
              }

              //获取curr_person的ParentCoupleId
              let ParentCoupleId = 0
              for (let i = 0; i < family_data.length; i++) {
                if (family_data[i].husband == this.data.curr_person || family_data[i].wife == this.data.curr_person) {
                  ParentCoupleId = family_data[i].parent
                  break
                }
              }

              //编辑信息
              wx.navigateTo({
                url: '../relation/add_father?family=' + app.globalData.select_family_id + '&select_family=' + selectFamilyId + '&select_person=' + selectPersonId + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&parent_couple_id=' + ParentCoupleId
              })
            })
          }
        },
        fail: res => {
          console.log(res.errMsg)
        }
      })

    } else {
      wx.navigateTo({
        url: '../relation/add_father?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name)
      })
    }
  },

  //添加母亲
  onAddMother() {
    if (0 == this.data.curr_person) {
      return
    }
    if (this.data.other_family_exist) {
      wx.showActionSheet({
        itemList: ['新增人员', '从其它家族中选择已有人员'],
        success: res => {
          console.log(res.tapIndex)
          if (res.tapIndex == 0) {
            //新增人员
            wx.navigateTo({
              url: '../relation/add_mother?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name)
            })

          } else if (res.tapIndex == 1) {
            //从其它家族中选择已有人员
            app.navigateToOtherFamilyMember(0, (selectFamilyId, selectPersonId) => {
              console.log('select person:', selectPersonId)

              if (!this.data.family_data) {
                this.setData({
                  family_data: this.tree_drawer.GetCurrWithLevelData()
                })
              }
              let family_data = this.data.family_data
              for (let i = 0; i < family_data.length; i++) {
                if (family_data[i].husband != 0 && family_data[i].husband == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
                if (family_data[i].wife != 0 && family_data[i].wife == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
              }

              //获取curr_person的ParentCoupleId
              let ParentCoupleId = 0
              for (let i = 0; i < family_data.length; i++) {
                if (family_data[i].husband == this.data.curr_person || family_data[i].wife == this.data.curr_person) {
                  ParentCoupleId = family_data[i].parent
                  break
                }
              }

              //编辑信息
              wx.navigateTo({
                url: '../relation/add_mother?family=' + app.globalData.select_family_id + '&select_family=' + selectFamilyId + '&select_person=' + selectPersonId + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&parent_couple_id=' + ParentCoupleId
              })
            })
          }
        },
        fail: res => {
          console.log(res.errMsg)
        }
      })

    } else {
      wx.navigateTo({
        url: '../relation/add_mother?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name)
      })
    }
  },

  //添加丈夫
  onAddHusband(){
    if (0 == this.data.curr_person) {
      return
    }
    if (!this.data.family_data) {
      this.setData({
        family_data: this.tree_drawer.GetCurrWithLevelData()
      })
    }
    //获取curr_person的priority
    let priority = 0
    let family_data = this.data.family_data
    for (let i = 0; i < family_data.length; i++) {
      if (family_data[i].husband == this.data.curr_person || family_data[i].wife == this.data.curr_person) {
        priority = family_data[i].priority
        break
      }
    }
    if (0 == priority) {
      return
    }
    if (this.data.other_family_exist) {
      wx.showActionSheet({
        itemList: ['新增人员', '从其它家族中选择已有人员'],
        success: res => {
          console.log(res.tapIndex)
          if (res.tapIndex == 0) {
            //新增人员
            wx.navigateTo({
              url: '../relation/add_husband?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&priority=' + priority
            })

          } else if (res.tapIndex == 1) {
            //从其它家族中选择已有人员
            app.navigateToOtherFamilyMember(1, (selectFamilyId, selectPersonId) => {
              console.log('select person:', selectPersonId)

              for (let i = 0; i < family_data.length; i++) {
                if (family_data[i].husband != 0 && family_data[i].husband == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
                if (family_data[i].wife != 0 && family_data[i].wife == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
              }

              //编辑信息
              wx.navigateTo({
                url: '../relation/add_husband?family=' + app.globalData.select_family_id + '&select_family=' + selectFamilyId + '&select_person=' + selectPersonId + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&priority=' + priority
              })
            })
          }
        },
        fail: res => {
          console.log(res.errMsg)
        }
      })

    } else {
      wx.navigateTo({
        url: '../relation/add_husband?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&priority=' + priority
      })
    }
  },

  //添加妻子
  onAddWife() {
    if (0 == this.data.curr_person) {
      return
    }
    if (!this.data.family_data) {
      this.setData({
        family_data: this.tree_drawer.GetCurrWithLevelData()
      })
    }
    //获取curr_person的priority
    let priority = 0
    let family_data = this.data.family_data
    for (let i = 0; i < family_data.length; i++) {
      if (family_data[i].husband == this.data.curr_person || family_data[i].wife == this.data.curr_person) {
        priority = family_data[i].priority
        break
      }
    }
    if (0 == priority) {
      return
    }
    if (this.data.other_family_exist) {
      wx.showActionSheet({
        itemList: ['新增人员', '从其它家族中选择已有人员'],
        success: res => {
          console.log(res.tapIndex)
          if (res.tapIndex == 0) {
            //新增人员
            wx.navigateTo({
              url: '../relation/add_wife?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&priority=' + priority
            })

          } else if (res.tapIndex == 1) {
            //从其它家族中选择已有人员
            app.navigateToOtherFamilyMember(0, (selectFamilyId, selectPersonId) => {
              console.log('select person:', selectPersonId)

              if (!this.data.family_data) {
                this.setData({
                  family_data: this.tree_drawer.GetCurrWithLevelData()
                })
              }
              let family_data = this.data.family_data
              for (let i = 0; i < family_data.length; i++) {
                if (family_data[i].husband != 0 && family_data[i].husband == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
                if (family_data[i].wife != 0 && family_data[i].wife == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
              }

              //编辑信息
              wx.navigateTo({
                url: '../relation/add_wife?family=' + app.globalData.select_family_id + '&select_family=' + selectFamilyId + '&select_person=' + selectPersonId + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&priority=' + priority
              })
            })
          }
        },
        fail: res => {
          console.log(res.errMsg)
        }
      })

    } else {
      wx.navigateTo({
        url: '../relation/add_wife?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&priority=' + priority
      })
    }
  },

  //添加子女
  onAddChild(){
    if (0 == this.data.curr_person) {
      return
    }
    if (!this.data.family_data) {
      this.setData({
        family_data: this.tree_drawer.GetCurrWithLevelData()
      })
    }
    let family_data = this.data.family_data
    let curr_couple = 0
    for (let i = 0; i < family_data.length; i++) {
      if (family_data[i].husband == this.data.curr_person || family_data[i].wife == this.data.curr_person) {
        curr_couple = family_data[i].child
        break
      }
    }
    if (0 == curr_couple) {
      return
    }

    if (this.data.other_family_exist) {
      wx.showActionSheet({
        itemList: ['新增人员', '从其它家族中选择已有人员'],
        success: res => {
          console.log(res.tapIndex)
          if (res.tapIndex == 0) {
            //新增人员
            wx.navigateTo({
              url: '../relation/add_child?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&target_couple_id=' + curr_couple
            })

          } else if (res.tapIndex == 1) {
            //从其它家族中选择已有人员
            app.navigateToOtherFamilyMember(-1, (selectFamilyId, selectPersonId) => {
              console.log('select person:', selectPersonId)
              for (let i = 0; i < family_data.length; i++) {
                if (family_data[i].husband != 0 && family_data[i].husband == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
                if (family_data[i].wife != 0 && family_data[i].wife == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
              }

              //编辑信息
              wx.navigateTo({
                url: '../relation/add_child?family=' + app.globalData.select_family_id + '&select_family=' + selectFamilyId + '&select_person=' + selectPersonId + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&target_couple_id=' + curr_couple
              })
            })
          }
        },
        fail: res => {
          console.log(res.errMsg)
        }
      })

    } else {
      wx.navigateTo({
        url: '../relation/add_child?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&target_couple_id=' + curr_couple
      })
    }
  },

  //添加兄弟姊妹
  onAddBrother(){
    if (0 == this.data.curr_person) {
      return
    }
    if (!this.data.family_data) {
      this.setData({
        family_data: this.tree_drawer.GetCurrWithLevelData()
      })
    }

    let family_data = this.data.family_data
    let curr_couple = 0
    let priority = 0
    let ParentCoupleId = 0
    for (let i = 0; i < family_data.length; i++) {
      if (family_data[i].husband == this.data.curr_person || family_data[i].wife == this.data.curr_person) {
        curr_couple = family_data[i].child
        priority = family_data[i].priority
        ParentCoupleId = family_data[i].parent
        break
      }
    }
    if (0 == curr_couple) {
      return
    }
    if (0 == priority) {
      return
    }

    if (this.data.other_family_exist) {
      wx.showActionSheet({
        itemList: ['新增人员', '从其它家族中选择已有人员'],
        success: res => {
          console.log(res.tapIndex)
          if (res.tapIndex == 0) {
            //新增人员
            wx.navigateTo({
              url: '../relation/add_brother?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&target_couple_id=' + curr_couple + '&priority=' + priority + '&parent_couple_id=' + ParentCoupleId
            })

          } else if (res.tapIndex == 1) {
            //从其它家族中选择已有人员
            app.navigateToOtherFamilyMember(-1, (selectFamilyId, selectPersonId) => {
              console.log('select person:', selectPersonId)
              for (let i = 0; i < family_data.length; i++) {
                if (family_data[i].husband != 0 && family_data[i].husband == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
                if (family_data[i].wife != 0 && family_data[i].wife == selectPersonId) {
                  app.showTip('本家族中已经存在此人，不能添加')
                  return
                }
              }

              //编辑信息
              wx.navigateTo({
                url: '../relation/add_brother?family=' + app.globalData.select_family_id + '&select_family=' + selectFamilyId + '&select_person=' + selectPersonId + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&target_couple_id=' + curr_couple + '&priority=' + priority + '&parent_couple_id=' + ParentCoupleId
              })
            })
          }
        },
        fail: res => {
          console.log(res.errMsg)
        }
      })

    } else {
      wx.navigateTo({
        url: '../relation/add_brother?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name) + '&target_couple_id=' + curr_couple + '&priority=' + priority + '&parent_couple_id=' + ParentCoupleId
      })
    }
  },

  onDeletePerson() {
    wx.showModal({
      title: '警告',
      confirmColor: '#FF0000',
      content: '确定删除人员：' + this.data.curr_person_name + ' 吗？',
      success: res => {
        if (res.confirm) {
          console.log('点击确定')

          app.httpRequest('family_delete_person', {
            family: app.globalData.select_family_id,
            target_person: this.data.curr_person
          }, res => {
            console.log('family_delete_person succ: ', res)
      
            this.refreshPersons(res)
      
          }, res => {
            console.log('family_delete_person failed: ', res)
          })

        } else if (res.cancel) {
          console.log('点击取消')
        }
      }
    })
  },

  //有人员改动，刷新所有人员
  refreshPersons(data) {
    console.log('refresh persons ...')
    this.tree_drawer.SetData(app.globalData.select_family_id, data)
    this.setData({
      family_data: null, //需要再刷新
      curr_person: 0,  //当前选中人
      curr_person_name: '',  //当前选中人的姓名
      curr_operations: [],
      has_edit_person: true,  //有编辑过人员
      last_edit_family_data: data,
    })
  },

  //编辑人员
  onEditPerson(e) {
    wx.navigateTo({
      url: '../relation/relation_edit_person?family=' + app.globalData.select_family_id + '&target_person=' + this.data.curr_person + '&target_person_name=' + encodeURI(this.data.curr_person_name)
    })
  }
})